package com.autoagent.ai_live_master.webSocket.listener;

import com.autoagent.ai_live_master.common.event.LiveStreamingPlanEvent;
import com.autoagent.ai_live_master.webSocket.service.PuppeteerService;
import com.autoagent.ai_live_master.webSocket.service.WordCloudService;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 直播计划事件监听器
 * 监听话术执行计划的启动和停止事件，执行相应的Puppeteer操作
 */
@Slf4j
@Component
public class LiveStreamingPlanEventListener {

    @Autowired
    private PuppeteerService puppeteerService;

    @Autowired
    private WordCloudService wordCloudService;

    /**
     * 监听直播计划事件
     */
    @EventListener
    public void handleLiveStreamingPlanEvent(LiveStreamingPlanEvent event) {
        try {
            if ("start".equals(event.getAction())) {
                log.info("收到直播计划启动事件，房间ID: {}, 计划ID: {}", event.getRoomId(), event.getPlanId());
                puppeteerService.connect(event.getRoomId());
                
                // 启动时发送定式话术
                try {
                    wordCloudService.sendFormulaicScript(event.getRoomId());
                } catch (JsonProcessingException e) {
                    log.error("发送定式话术失败: {}", e.getMessage(), e);
                }
            } else if ("stop".equals(event.getAction())) {
                log.info("收到直播计划停止事件，房间ID: {}, 计划ID: {}", event.getRoomId(), event.getPlanId());
                puppeteerService.disconnect();
            }
        } catch (Exception e) {
            log.error("处理直播计划事件失败: {}", e.getMessage(), e);
        }
    }
}
